package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.kit.ValidateKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.AdminSeller;
import cn.com.dashihui.web.dao.Store;
import cn.com.dashihui.web.dao.StoreImages;
import cn.com.dashihui.web.service.StoreService;
@RequiresAuthentication
public class StoreController extends BaseController{
	private StoreService storeService = new StoreService();
    
	//@RequiresPermissions("dict:store:index")
    public void index(){
    	int userid=getCurrentUser().getInt("id");
    	Record st = storeService.findState(userid);
    	int RoleId = storeService.findByRoleId(userid);
    	 int state=1;
    	 int power=1;
		if(st!=null){
		 state= storeService.findState(userid).get("state");
		 power= storeService.findState(userid).get("power");
    	setAttr("state", state);
    	setAttr("power", power);
    	setAttr("RoleId", RoleId);
    /*	List<Record> list=storeService.findAllSeller();
    	setAttr("list", list);*/
        render("index.jsp");
		}else{
			setAttr("power", power);
			setAttr("state", state);
			setAttr("RoleId", RoleId);
			render("index.jsp");
		}
		
    }

    
    /**
     * //下线方法                            
     */
    public void Offline(){
    	String storeid=getPara("storeid");
    	String dowetime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    	if(StrKit.isBlank(storeid)){
			renderFailed("参数storeid不能为空");
    		return;
    	}else{
    		
    		int i= storeService.Offline(storeid,dowetime);
    		if(i==1){
    			renderSuccess(storeService.findByIdStoreid(storeid));
    			return ;
    		}else{
    			//3.其他情况
				renderFailed("下线失败");
				return;
    		}
    	}
    }
    //上线的方法
    public void Online(){
    	String storeid=getPara("storeid");
    	String starttime=DatetimeKit.getFormatDate("yyyy-MM-dd  HH:mm:ss");
    	if(StrKit.isBlank(storeid)){
			renderFailed("参数storeid不能为空");
    		return;
    	}else{
    		//int i= storeService.doCancel2(storeid,checktime);
    		int i= storeService.Online(storeid,starttime);
    		if(i==1){
    			renderSuccess(storeService.findByIdStoreid(storeid));
    			return ;
    		}else{
    			//3.其他情况
				renderFailed("上线失败");
				return;
    		}
    	}
    }
    
    /**
     * 驳回原因
     */
    public void toBoHui(){
    	String storeid=getPara("storeid");
    	if(StrKit.notBlank(storeid)){
			Store store=storeService.findByIdStoreid(storeid);
			String reason=store.getStr("reason");
			setAttr("reason", reason);
			render("bohui.jsp");;
    	}
    	else{
    		renderFailed("查看失败");
			return;
        }
    }
    /**
     * 分公司管理主页面的分页数据
     */
    public void page(){
    	int userid=getCurrentUser().getInt("id");
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		String storeid = getPara("storeid");
		String title = getPara("title");
		int state = Integer.parseInt(getPara("state"));
		//int qstate = Integer.parseInt(getPara("qstate"));	
		String sellerId=null;
		if(StrKit.notNull(storeService.findByUserId(userid)))
			{
			 sellerId=storeService.findByUserId(userid).get("sellerId");
			}
		
		renderResult(0,storeService.findByPage(pageNum, pageSize, storeid, state ,sellerId,title));
	}

	/**
	 * 转到增加分公司页面
	 */
	public void toAdd(){
		List<Record> list=storeService.findCity();
    	setAttr("list", list);
    	String stroeimagenum=DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.buildRandomNum(4);
    	setAttr("stroeimagenum", stroeimagenum);
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：用户名为空，2：用户名过长，3：用户已经存在，4：密码为空，5：密码过长，6：分公司名为空，7：分公司名过长，8：联系人姓名为空，9：联系人姓名过长......
	 */
	public void doAdd(){
		
		//UploadFile storethumb = getFile("storethumb");
		UploadFile busthumb = getFile("busthumb");
		//分公司名称
		String title = getPara("title");
		//分公司简称
		String shortName = getPara("shortName");
		//同步Id
		String BranchId=getPara("BranchId");
		//抵现比例
		String dixian=getPara("dixian");
		double dixians;
		if(StrKit.isBlank(dixian)){
			dixians=0;
		}else{
			dixians=Double.parseDouble(dixian);
		}
		
		//抵现积分类型
		String selectpoint=getPara("selectpoint");
		//所在城市
		int cityid= getParaToInt("cityid");
		//主营范围
		int scope = getParaToInt("scope",0);
		//社会统一信用代码
		String busLicense = getPara("busLicense");
		//分公司图片编号
		String stroeimagenum=getPara("stroeimagenum");
		//地理位置
		String address = getPara("address");
		//店内联系电话
		String tel = getPara("tel");
		//获取当前登录用户的id
		AdminSeller user=getCurrentUser();	
		int userid=user.getInt("id");
		//商店Id
		String storeid="DP"+userid+CommonKit.buildRandomNum(6);
			   
	    Record record=storeService.FindById(userid);
	    String sellerId=record.getStr("sellerId");    
		//联系人姓名
		String aname = getPara("aname");
		//联系人联系方式
		String aphone = getPara("aphone");
		int state =1;
		int qstate=1;
		/*//配送说明
		String deliverydes = getPara("deliverydes");
		//省、市、县/区
		int province = getParaToInt("province",0),city = getParaToInt("city",0),area = getParaToInt("area",0);
		//详细地址
		String address = getPara("address");*/
		if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else if(storeService.findExistsByTitle(title)){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(shortName)){
			renderResult(4);
			return;
		}else if(shortName.length()>100){
			renderResult(5);
			return;
		}
		else if(StrKit.isBlank(address)){
			renderResult(7);
			return;
		}else if(address.length()>2000){
			renderResult(8);
			return;
		}else if(scope==0){
			renderResult(9);
			return;
		}else if(!ValidateKit.Tel(tel) && !ValidateKit.Mobile(tel)){
			renderResult(10);
			return;
		}
		else if(!ValidateKit.Tel(aphone) && !ValidateKit.Mobile(aphone)){
			renderResult(11);
			return;
		}
		else if(storeService.findExistsByaphone(aphone)){
			renderResult(15);
			return;
		}
		else if(storeService.findExistsByStoreId(storeid)){
			renderResult(13);
			return;
		}else if(storeService.findExistsByTel(tel)){
			renderResult(14);
			return;
		}else{  
			//保存
			Store store = new Store()
				.set("title", title)
				.set("shortName", shortName)
				.set("BranchId", busLicense)
				.set("BranchId", BranchId)
				.set("city", cityid)
				.set("scope", scope)
				.set("stroeimagenum", stroeimagenum)
				.set("createtime",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				.set("starttime",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
				.set("address", address)
				.set("tel", tel)
				.set("storeid", storeid)
				.set("sellerId", sellerId)
				.set("aname", aname)
				.set("aphone", aphone)
				.set("state", state)
				.set("qstate", qstate)
				.set("predixian", dixians)
				.set("prepoint", selectpoint);
			
			//如果上传了图片，则上传至FTP，并记录图片文件名
			if(busthumb!=null){
				//String thumbFileName;
				String bustFileName;				
//				String dir = DirKit.getDir(DirKit.STORE_LOGO);
				String dirr = DirKit.getDir(DirKit.STORE_LOGO);
				try {
					//thumbFileName = uploadToFtp(dir,storethumb);
					bustFileName = uploadToFtp(dirr,busthumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(18);
					return;
				}
				//store.set("storethumb", dir.concat(thumbFileName));
				store.set("busthumb", dirr.concat(bustFileName));
			}
			storeService.addStore(store);
			
			
			/*if(storeService.addStore(store)){
				//同时用户表里注册，会员等级设置为分公司
				//电话
				 User userNew=storeService.getUserByPhone(aphone);
				//设置用户密码，默认为手机号后六位
				 String password = aphone.substring(aphone.length() - 6);
				 //改变用户等级
				 if (userNew!=null) {
					 userNew.set("taici", SysConfig.tBusUserTaici.level_6)
					 .set("storeName", title)
					 .set("babythday",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					 .set("storeid", storeid);
					 
					 userNew.set("password", CommonKit.encryptPassword(password));
					 if (userNew.update()) {
						 renderSuccess();
					} else {
						log.error("前端用户修改等级失败！");
					}
				} else {
					User user2 = new User();
					String date= DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
					user2.set("name", aname)
					 	 .set("phone", aphone)
					 	 .set("state", state)
					 	 .set("address", address)
					 	 .set("createDate", date)
					 	 .set("babythday",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					 	 .set("taici", SysConfig.tBusUserTaici.level_6)
					 	.set("storeid", storeid)
					 	.set("storeName", title)
					 	 .set("password", CommonKit.encryptPassword(password));//设置用户密码，默认为手机号后六位
					 if (user2.save()) {
						 renderSuccess();
					} else {
						log.error("前端用户添加失败！");
					}
				}
				renderSuccess();
				return;
			}*/
		}
		renderSuccess();
	}
	
	public void toEdit(){   
		
    	String id=getPara("id");
    	
    	List<Record> list=storeService.findCity();
    	//Record lis=storeService.EditCity(storeid);
    	setAttr("list", list);
		if(id!=null){
			setAttr("object", storeService.detail(id));
		}
		render("edit.jsp");
    }
	

	/**
	 * 更新
	 * @return -1：异常，0：成功，1：便利店名称为空，2：便利店名称过长，3：代码为空，4：代码过长，5：代码已经存在，6：详情地址为空，7：详细地址过长，8：图片为空，9：图片上传失败
	 */
	public void doEdit(){
		
		//UploadFile storethumb = getFile("storethumb");
		UploadFile busthumb = getFile("busthumb");
		//分公司表id
		String id=getPara("id");
		//分公司名称
		String title = getPara("title");
		//分公司简称
		String shortName = getPara("shortName");
		//社会统一信用代码
		String busLicense = getPara("busLicense");
		//同步Id
		String BranchId=getPara("BranchId");
		//抵现比例
		String dixian=getPara("dixian");
		//抵现积分类型
		String selectpoint=getPara("selectpoint");
		//所在城市
		int city= getParaToInt("city");
		//主营范围
		int scope = getParaToInt("scope",0);
		//分公司轮播图
		String stroeimagenum=getPara("stroeimagenum");
		//地理位置
		String address = getPara("address");
		//店内联系电话
		String tel = getPara("tel");	
		//联系人姓名
		String aname = getPara("aname");
		//联系人联系方式
		String aphone = getPara("aphone");
		int state =6;
		int qstate =1;
		//旧图片
		String thumbOldd = getPara("thumbOldd");
		if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>100){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(shortName)){
			renderResult(4);
			return;
		}else if(shortName.length()>100){
			renderResult(5);
			return;
		}
		else if(StrKit.isBlank(address)){
			renderResult(7);
			return;
		}else if(address.length()>2000){
			renderResult(8);
			return;
		}else if(scope==0){
			renderResult(9);
			return;
		}
		else if(!ValidateKit.Tel(aphone) && !ValidateKit.Mobile(aphone)){
			renderResult(11);
			return;
			
		} else{
			//更新
			Store store =storeService.findStroe(Integer.valueOf(id))
					.set("title", title)
					.set("shortName", shortName)
					.set("BranchId", busLicense)
					.set("BranchId", BranchId)
					.set("scope", scope)
					.set("stroeimagenum", stroeimagenum)
					.set("city", city)
					.set("address", address)
					.set("starttime",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("tel", tel)					
					.set("aname", aname)
					.set("aphone", aphone)
					.set("state", state)
					.set("qstate", qstate)
					.set("predixian", dixian)
					.set("prepoint", selectpoint);
				
			if(busthumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
				//String thumbFileName;
				String bustFileName;				
				//String dir = DirKit.getDir(DirKit.STORE_LOGO);
				String dirr = DirKit.getDir(DirKit.STORE_LOGO);
				try {
					//thumbFileName = uploadToFtp(dir,storethumb);
					bustFileName = uploadToFtp(dirr,busthumb);
					//deleteFromFtp(thumbOld);
					deleteFromFtp(thumbOldd);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(6);
					return;
				}
				//store.set("storethumb", dir.concat(thumbFileName));
				store.set("busthumb", dirr.concat(bustFileName));
			}
			
			if(storeService.editStore(store)){
				renderSuccess(storeService.findByIdStore(Integer.valueOf(id)));
				return;
			}
		}
		renderFailed();
	}
	
	
	public void toEditPwd(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", storeService.findById(id));
		}
		render("editPwd.jsp");
	}
	
/**
 * 编辑图片
 * 
 */
public void doPicture(){
		
		UploadFile storethumb = getFile("storethumb");	
		
		//分公司表id
		String id=getPara("id");	
		//旧图片
		String thumbOld = getPara("thumbOld");
		
		
			//int idd = Integer.valueOf(id);
			Store store = new Store()
					.set("id", id);			
			if(storethumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
    			String thumbFileName;						
				String dir = DirKit.getDir(DirKit.STORE_LOGO);	
				try {
					thumbFileName = uploadToFtp(dir,storethumb);				
					deleteFromFtp(thumbOld);				
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(6);
					return;
				}	
				store.set("storethumb", dir.concat(thumbFileName));
				storeService.editStore(store);
					index();
						return;
					
				
			}else if(thumbOld==null){
				String thumbFileName;			
				String dir = DirKit.getDir(DirKit.STORE_LOGO);			
				try {
					thumbFileName = uploadToFtp(dir,storethumb);			
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(18);
					return;
				}
				store.set("storethumb", dir.concat(thumbFileName));
				storeService.editStore(store);
				index();
			}else if(storethumb==null){
			     
				
					index();
					
			}
			
				renderFailed();
	
			}
	
	
	/**
	 * 更新密码
	 * @return -1：异常，0：成功，1：密码为空，2：密码过长
	 */
	public void doEditPwd(){
		//分公司ID0
		String storeid = getPara("storeid");
		//密码
		String password = getPara("password");
		if(StrKit.isBlank(storeid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(password)){
			renderResult(1);
			return;
		}else if(password.length()>100){
			renderResult(2);
			return;
		}else{
			//更新
			if(storeService.editStore(new Store()
				.set("id", storeid)
				.set("password", new DefaultPasswordService().encryptPassword(password)))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}
	/**
	 * 分公司图的添加图片的页面
	 */
	public void imageIndex(){
		String stroeimagenum =getPara(0);
		setAttr("stroeimagenum",stroeimagenum);
        render("storeimageList.jsp");
    }	
	/**
	 * 图片分页
	 */
    public void imagePage(){
    	String stroeimagenum =getPara(0);		
    	renderSuccess(storeService.findAllImages(stroeimagenum));
    }
    /**
     * 图片排序
     */
    public void doImageSort(){
    	Map<String,String[]> params = getParaMap();
    	if(params!=null&&params.size()!=0&&params.containsKey("sortKey")){
    		String sortKey = params.get("sortKey")[0];
    		Map<String,String> sortMap = new HashMap<String,String>();
    		for(String key : params.keySet()){
    			if(!key.equals("sortKey")){
    				String id = key.replace(sortKey, "");
    				String no = params.get(key)[0];
    				if(StrKit.isBlank(no)||no.length()>3){
    					no = "0";
    				}
    				sortMap.put(id, no);
    			}
    		}
    		storeService.sortImages(sortMap);
    		renderSuccess();
    		return;
    	}
    	renderFailed();
    }
    /**
     * 添加图片
     */
	public void toImageAdd(){
		String stroeimagenum =getPara(0);
		setAttr("stroeimagenum",stroeimagenum);	
		render("imageAdd.jsp");
	}
	/**
	 * 添加图片
	 * @return -1：异常，0：成功，1：图片为空，2：图片上传失败
	 */
	public void doImageAdd(){
		UploadFile thumb = getFile("thumb");
		String stroeimagenum =getPara("stroeimagenum");
		//保存
		//如果上传了图片，则上传至FTP，并记录图片文件名
		if(thumb!=null){
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.STORE_LOGO);
			try {
				thumbFileName = uploadToFtp(dir,thumb);
			} catch (IOException e) {
				e.printStackTrace();
				renderResult(2);
				return;
			}
			StoreImages image = new StoreImages().set("stroeimagenum", stroeimagenum).set("thumb", dir.concat(thumbFileName));
			if(storeService.addImage(image)){
				renderSuccess(image);
				return;
			}
		}else{
			renderResult(1);
			return;
		}
	}
	/**
	 * 删除图片
	 * @param id
	 * @return
	 */
	public void doImageDelete(){
		int id = getParaToInt(0,0);
		if(id!=0&&storeService.delImage(id)){
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/*public boolean delImage(int id){
		return StoreImages.me().deleteById(id);
	}*/

	/**
	 * excel导出
	 */
	public void doExcel(){
	  String operationMsg = "excel导出";
	  logger.info(operationMsg);
		List<Pair> titles = new ArrayList<Pair>();
	    titles.add(new Pair("storeid", "分公司ID"));
	    titles.add(new Pair("title", "分公司名称"));
	    titles.add(new Pair("scope", "主营范围"));
	    titles.add(new Pair("aname", "联系人"));
	    titles.add(new Pair("aphone", "联系电话"));
	    titles.add(new Pair("address", "分公司位置"));
	    titles.add(new Pair("qstate", "分公司状态"));
	    titles.add(new Pair("createtime", "创建时间"));
	    titles.add(new Pair("starttime", "上线时间"));
	    titles.add(new Pair("downtime", "下线时间"));
	    int userid=getCurrentUser().getInt("id");
		int RoleId= storeService.findByRoleId(userid);
		int state = Integer.parseInt(getPara("state"));
		int qstate = Integer.parseInt(getPara("qstate"));
 		String storeid = null;
 		String sellerId =null;
 		if(RoleId==1||RoleId==2&&StrKit.notNull(storeService.findByUserId(userid))){
 			sellerId =storeService.findByUserId(userid).get("sellerId");
 			storeid =getPara("storeid");
 		}else if(StrKit.notNull(storeService.findStoreState(userid))){
 			storeid =storeService.findStoreState(userid).get("storeid");
 			}
		List<Record> list=storeService.findExcelByPage(state ,qstate,storeid,sellerId);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
				record.set("storeid",list.get(i).get("storeid"));
				record.set("title", list.get(i).get("title"));
				if(list.get(i).get("scope").equals(1)){
					record.set("scope", "常规");
				}else if(list.get(i).get("scope").equals(2)){
					record.set("scope", "团购");
				}else{
					record.set("scope", "常规+团购");
				}
				record.set("aname", list.get(i).get("aname"));
				record.set("aphone", list.get(i).get("aphone"));
				record.set("address", list.get(i).get("address"));
					if(list.get(i).get("qstate").equals(1)){
						if(list.get(i).get("state").equals(1)){
							record.set("qstate", "上线审核中");
						}else if(list.get(i).get("state").equals(2)){
							record.set("qstate", "上线");
						}else if(list.get(i).get("state").equals(3)){
							record.set("qstate", "下线");
						}
					}else if(list.get(i).get("qstate").equals(2)){
						record.set("qstate", "禁货");
					}else if (list.get(i).get("qstate").equals(3)){
						record.set("qstate", "降权");
					}
				record.set("createtime", list.get(i).get("createtime"));
				record.set("starttime", list.get(i).get("starttime"));
				record.set("downtime", list.get(i).get("downtime"));
			listz.add(record);
 		}
		// 导出
		storeService.export(getResponse(), getRequest(),titles, listz);		
		logger.info( "成功");
		renderNull();
	}
	
}
